package room

import (
	"errors"
	"log"
	"strconv"
	"github.com/gorilla/websocket"
)

func Init() {
	RoomList=RoomMap{}
}

func newRoom(HostUid uint32,roomid int) *Gameroom{
	g:=new(Gameroom)
	g.HostUid=roomid
	g.Group=map[uint32]member{}
	g.Begin=false
	g.uuid=generateuuid()

	return g
}

//添加玩家
func (g *Gameroom) addPlayer(uid uint32,name string,conn *websocket.Conn) bool{
	if g.CheckExist(uid){
		g.Group[uid].Conn.Close()
		g.Group[uid]=member{
			Conn:conn,
			Name:name,
		}
		return false
	}
	g.Group[uid]=member{
		Conn:conn,
		Name:name,
	}
	return true
}


func ConnectRoom(uid uint32,name string,roomid int,conn *websocket.Conn) (error){
	if roomid<100000||roomid>=1000000{
		return errors.New("房间不存在")
	}

	m,ok:=RoomList[roomid]
	if !ok{
		g:=newRoom(uid, roomid)
		RoomList[roomid]=g
		
		g.Mu.Lock()
		g.addPlayer(uid,name,conn)
		err:=conn.WriteJSON(Wmessage{Data:[]string{name},Order:0})
		if err!=nil{
			conn.Close()
			log.Println(err)
		}
		g.Mu.Unlock()
		return err
	}

	m.Mu.Lock()
	defer m.Mu.Unlock()

	if len(m.Group)==4{
		return errors.New("房间已满")
	}
	ok=m.addPlayer(uid,name,conn)
	if !ok{
		log.Println("玩家重连"+strconv.Itoa(int(uid)))
		return nil
	}

	s:=[]string{}
	for _,v:=range m.Group{
		s=append(s,v.Name)
	}

	err:=conn.WriteJSON(Wmessage{Data:s,Order:0})
	if err!=nil{
		conn.Close()
		log.Println(err)
	}

	for _,v:=range m.Group{
		if v.Conn==conn{
			continue
		}
		err:=v.Conn.WriteJSON(Wmessage{Data:[]string{name},Order:1})
		if err!=nil{
			v.Conn.Close()
			log.Println(err)
		}
	}

	return nil
}

//删除玩家
func (g *Gameroom) DelPlayer(uid int) bool{
	g.Mu.Lock()
	defer g.Mu.Unlock()

	delete(g.Group,uint32(uid))

	return false
}
func (g *Gameroom)CheckExist(uid uint32) bool {
	if g==nil{
		return false
	}
	if _,ok:=g.Group[uid];ok{
		return true
	}
	return false
}

func (g *Gameroom)RoomToGame() { 
	g.Mu.Lock()
	g.Begin=true
	g.Mu.Unlock()
}




